package com.example.user.myfirstapp.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.example.user.myfirstapp.MyApplication;
import com.example.user.myfirstapp.R;
import com.example.user.myfirstapp.common.Constant;
import com.example.user.myfirstapp.common.ImageHelper;
import com.example.user.myfirstapp.common.LoadingDialog;
import com.example.user.myfirstapp.common.StringHelper;
import com.example.user.myfirstapp.entity.Comment;
import com.example.user.myfirstapp.entity.Goods;
import com.example.user.myfirstapp.entity.GoodsImages;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by user on 2016/6/28.
 */
public class GoodsInfoActivity extends Activity implements View.OnClickListener{
    private Button bt_goodsinfo_return,bt_goodsinfo_buy,bt_goodsinfo_add,bt_goodsinfo_collect,bt_goodsinfo_car;
    private TextView tv_top_name,tv_goodsinfo_name,tv_goodsinfo_price,tv_goodsinfo_marketprice,tv_goodsinfo_integral,tv_goodsinfo_num,tv_goodsinfo_comment;
    private PullToRefreshScrollView mPullRefreshSrollView,goodsimginfo_refresh_scrollview;
    private LinearLayout ll_goodsinfo_up,ll_goodsinfo_num,ll_goodsinfo_comment;
    private Intent intent;
    private ViewPager viewPager;
    private ViewGroup group;
    private Gson gson;
    private Goods goods;
    private List<GoodsImages> goodsImagesList;
    /**
     * 装点点的ImageView数组
     */
    private ImageView[] tips;
    /**
     * 装ImageView数组
     */
    private NetworkImageView[] mImageViews;
    //商品图片的个数
    private int imglistLength;
    private WebView wv_goodsinfo;
    private PopupWindow mPopWindow;
    private String commentJson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goodsinfo);

        mPullRefreshSrollView=(PullToRefreshScrollView)findViewById(R.id.goodsinfo_refresh_scrollview);
        goodsimginfo_refresh_scrollview=(PullToRefreshScrollView)findViewById(R.id.goodsimginfo_refresh_scrollview);
        wv_goodsinfo=(WebView)findViewById(R.id.wv_goodsinfo);
        tv_top_name=(TextView)findViewById(R.id.tv_top_name);
        tv_goodsinfo_comment=(TextView)findViewById(R.id.tv_goodsinfo_comment);
        tv_goodsinfo_name=(TextView)findViewById(R.id.tv_goodsinfo_name);
        tv_goodsinfo_price=(TextView)findViewById(R.id.tv_goodsinfo_price);
        tv_goodsinfo_marketprice=(TextView)findViewById(R.id.tv_goodsinfo_marketprice);
        tv_goodsinfo_integral=(TextView)findViewById(R.id.tv_goodsinfo_integral);
        tv_goodsinfo_num=(TextView)findViewById(R.id.tv_goodsinfo_num);
        bt_goodsinfo_return=(Button)findViewById(R.id.bt_goodsinfo_return);
        bt_goodsinfo_return.setOnClickListener(this);
        ll_goodsinfo_up=(LinearLayout)findViewById(R.id.ll_goodsinfo_up);
        ll_goodsinfo_up.setOnClickListener(this);
        ll_goodsinfo_num=(LinearLayout)findViewById(R.id.ll_goodsinfo_num);
        ll_goodsinfo_num.setOnClickListener(this);

        group = (ViewGroup)findViewById(R.id.ll_viewGroup);
        viewPager = (ViewPager) findViewById(R.id.gddsinfo_viewPager);


        intent =getIntent();
        goods =(Goods)intent.getSerializableExtra("goods");
        if(goods!=null){
            loadGoodsInfo(goods);
        }
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_goodsinfo_return:
                this.finish();
                //从左往右切换
                this.overridePendingTransition(0,R.animator.slide_right_out);
                break;
            case R.id.ll_goodsinfo_up:
                int top = 0;
                int left = goodsimginfo_refresh_scrollview.getLeft();
                int right = goodsimginfo_refresh_scrollview.getRight();
                int bottom = goodsimginfo_refresh_scrollview.getBottom();
                mPullRefreshSrollView.setVisibility(View.GONE);//隐藏mPullRefreshSrollView
                goodsimginfo_refresh_scrollview.layout(left, top, right, bottom);//改变goodsimginfo_refresh_scrollview的位置
                break;
            case R.id.ll_goodsinfo_num:
                showPopupWindow();
                break;
            case R.id.ll_goodsinfo_comment:
                intent =new Intent(this,GoodsCommentActivity.class);
                intent.putExtra("commentJson",commentJson);
                startActivity(intent);
                //从右往左切换
                overridePendingTransition(R.animator.slide_right_in,0);
                break;
            default:
                break;
        }
    }

    private void loadGoodsInfo(Goods goods){
        try {
            //显示加载中
            LoadingDialog.showLoading(this,"请稍后...");
            //头部标题
            tv_top_name.setText(StringHelper.cutString(goods.getGoodsName(),25));
            //商品图片滚动
            imagesPlay(goods.getGoodsId());
            //中间标题
            tv_goodsinfo_name.setText(goods.getGoodsName());
            //价格
            tv_goodsinfo_marketprice.setText("￥"+String.valueOf(goods.getGoodsMarketPrice()));
            //原价
            tv_goodsinfo_price.setText("￥"+String.valueOf(goods.getGoodsPrice()));
            tv_goodsinfo_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//字体中间加横线
            //积分
            tv_goodsinfo_integral.setText(String.valueOf(goods.getGoodsIntegral())+"积分");

            //PullRefreshSrollView
            initPullToRefreshListView();

            //图文详情
            WebSettings webSettings = wv_goodsinfo.getSettings();
            webSettings.setJavaScriptEnabled(true);// JavaScript使能(如果要加载的页面中有JS代码，则必须使能JS)
            webSettings.setDefaultTextEncodingName("utf-8") ;
            //wv_goodsinfo.loadData(goods.getGoodsContent(),"text/html","utf-8");//API提供的标准用法，无法解决乱码问题
            wv_goodsinfo.loadData(goods.getGoodsContent(), "text/html; charset=UTF-8", null);//这种写法可以正确解码

            //评论
            getComment(goods.getGoodsId());
        }
        catch (Exception e){
        }
    }

    /***********************************************************************************************
     * 图片滚动
     * */
    private void imagesPlay(int goodsId){
        String url = "http://"+ Constant.host+":"+Constant.port+"/api/GoodsImages/GetListByGoodsId/"+goodsId;
        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        showimgList(result);
                        //关闭提示语
                        LoadingDialog.closeLoading();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(GoodsInfoActivity.this, "网络请求失败",
                                Toast.LENGTH_LONG).show();
                        //关闭提示语
                        LoadingDialog.closeLoading();
                    }
                }
        );
        request.setTag("getGoodsImgList");
        MyApplication.getHttpQueue().add(request);
    }
    private void showimgList(String json){
        String baseUrl="http://"+ Constant.host+":"+Constant.port;
        gson = new Gson();
        goodsImagesList=new ArrayList<GoodsImages>();
        goodsImagesList = gson.fromJson(json,new TypeToken<List<GoodsImages>>(){}.getType());
        imglistLength=goodsImagesList.size();
        if(imglistLength>0){
            //将点点加入到ViewGroup中
            tips = new ImageView[imglistLength];
            for (int i = 0; i < imglistLength; i++) {
                ImageView imageView = new ImageView(this);
                imageView.setLayoutParams(new ViewGroup.LayoutParams(10, 10));
                tips[i] = imageView;
                if (i == 0) {
                    tips[i].setBackgroundResource(R.mipmap.page_indicator_focused);
                } else {
                    tips[i].setBackgroundResource(R.mipmap.page_indicator_unfocused);
                }
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
                layoutParams.leftMargin = 5;
                layoutParams.rightMargin = 5;
                group.addView(imageView, layoutParams);
            }

            //将图片装载到数组中
            int mImageViewsLength=0;
            //如果是1张图片
            if (imglistLength == 1){
                mImageViews = new NetworkImageView[4];
                mImageViewsLength=mImageViews.length;
                for (int i = 0; i < mImageViewsLength; i++) {
                    NetworkImageView imageView = new NetworkImageView(this);
                    mImageViews[i] = imageView;
                    ImageHelper.showImageByNetworkImageView(MyApplication.getHttpQueue(), imageView, baseUrl+goodsImagesList.get(0).getImageUrl());
                }
                group.setVisibility(View.GONE);
            }
            //如果是2张或3张图片
            else if (imglistLength == 2 || imglistLength == 3) {
                mImageViews = new NetworkImageView[imglistLength * 2];
                mImageViewsLength=mImageViews.length;
                for (int i = 0; i < mImageViewsLength; i++) {
                    NetworkImageView imageView = new NetworkImageView(this);
                    mImageViews[i] = imageView;
                    int p=(i > (imglistLength-1)) ? i -imglistLength : i;
                    ImageHelper.showImageByNetworkImageView(MyApplication.getHttpQueue(), imageView, baseUrl+goodsImagesList.get(p).getImageUrl());
                }
            }
            else {
                mImageViews = new NetworkImageView[imglistLength];
                mImageViewsLength=mImageViews.length;
                for (int i = 0; i < mImageViewsLength; i++) {
                    NetworkImageView imageView = new NetworkImageView(this);
                    mImageViews[i] = imageView;
                    ImageHelper.showImageByNetworkImageView(MyApplication.getHttpQueue(), imageView, baseUrl+goodsImagesList.get(i).getImageUrl());
                }
            }

            //设置Adapter
            viewPager.setAdapter(new MyAdapter());
            //设置监听，主要是设置点点的背景
            viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                }
                @Override
                public void onPageSelected(int position) {
                    setImageBackground(position % imglistLength);
                }
                @Override
                public void onPageScrollStateChanged(int state) {
                }
            });
            viewPager.setCurrentItem(0);
            //这里不自动滚动
            //mHandler.postDelayed(mRunnable, 4000);
        }
    }
//    private Handler mHandler =  new Handler();
//    private Runnable mRunnable = new Runnable() {
//        public void run() {
//            //每隔多长时间执行一次
//            mHandler.postDelayed(mRunnable, 4000);
//            currposition++;
//            viewHandler.sendEmptyMessage(currposition);
//        }
//    };
//    private final Handler viewHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            viewPager.setCurrentItem(msg.what);
//            super.handleMessage(msg);
//        }
//    };
    public class MyAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }
        // 来判断显示的是否是同一张图片，这里我们将两个参数相比较返回即可
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }
        /**
         * PagerAdapter只缓存三张要显示的图片，如果滑动的图片超出了缓存的范围，就会调用这个方法，将图片销毁
         */
        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager)container).removeView(mImageViews[position % mImageViews.length]);
        }
        /**
         * 载入图片进去，用当前的position 除以 图片数组长度取余数是关键
         */
        @Override
        public Object instantiateItem(View container, int position) {
            int p=position % mImageViews.length;
            try {
                ((ViewPager)container).addView(mImageViews[p], 0);
            }catch(Exception e){
                //handler something
            }
            return mImageViews[p];
        }
    }
    /**
     * 设置选中的tip的背景
     * @param selectItems
     */
    private void setImageBackground(int selectItems){
        for(int i=0; i<tips.length; i++){
            if(i == selectItems){
                tips[i].setBackgroundResource(R.mipmap.page_indicator_focused);
            }else{
                tips[i].setBackgroundResource(R.mipmap.page_indicator_unfocused);
            }
        }
    }
    /***********************************************************************************************
     * 图片滚动 end
     * */

    private void initPullToRefreshListView(){
        mPullRefreshSrollView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);//xml里也有设置
        //去除上拉时的加载动画和文字
        ILoadingLayout endLabels = mPullRefreshSrollView.getLoadingLayoutProxy(false,true);
        endLabels.setLoadingDrawable(null);
        endLabels.setPullLabel("");
        endLabels.setRefreshingLabel("");
        endLabels.setReleaseLabel("");
        //刷新
        mPullRefreshSrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
            }

            //上拉
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                int top = 0;
                int left = goodsimginfo_refresh_scrollview.getLeft();
                int right = goodsimginfo_refresh_scrollview.getRight();
                int bottom = goodsimginfo_refresh_scrollview.getBottom();

                mPullRefreshSrollView.setVisibility(View.GONE);//隐藏mPullRefreshSrollView
                goodsimginfo_refresh_scrollview.layout(left, top, right, bottom);//改变goodsimginfo_refresh_scrollview的位置

                mPullRefreshSrollView.onRefreshComplete();
            }
        });

        //去除下拉时的加载动画和文字
        ILoadingLayout startLabels = goodsimginfo_refresh_scrollview.getLoadingLayoutProxy(true,false);
        startLabels.setLoadingDrawable(null);
        startLabels.setPullLabel("");
        startLabels.setRefreshingLabel("");
        startLabels.setReleaseLabel("");
        //刷新
        goodsimginfo_refresh_scrollview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            //下拉
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                int height=mPullRefreshSrollView.getHeight();
                int left = goodsimginfo_refresh_scrollview.getLeft();
                int right = goodsimginfo_refresh_scrollview.getRight();
                int bottom = goodsimginfo_refresh_scrollview.getBottom();

                mPullRefreshSrollView.setVisibility(View.VISIBLE);//显示mPullRefreshSrollView
                goodsimginfo_refresh_scrollview.layout(left, height, right, bottom);//改变goodsimginfo_refresh_scrollview的位置

                goodsimginfo_refresh_scrollview.onRefreshComplete();
            }

            //上拉
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
            }
        });
    }

    //显示PopupWindow
    private void showPopupWindow(){
        //设置contentView
        View contentView = LayoutInflater.from(this).inflate(R.layout.popup_setnum, null);
        mPopWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        mPopWindow.setAnimationStyle(R.style.popupWindowAnim);
        mPopWindow.setOutsideTouchable(true);
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_goodsinfo, null);
        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);

        //库存数
        TextView tv_goods_store=(TextView)contentView.findViewById(R.id.tv_goods_store);
        tv_goods_store.setText(String.valueOf(goods.getGoodsStoreNum()));

        //已选数量
        final EditText et_goods_store=(EditText)contentView.findViewById(R.id.et_goods_store);
        et_goods_store.setText(tv_goodsinfo_num.getText());

        //点击PopWindow阴影事件
        RelativeLayout rl_popupbox=(RelativeLayout)contentView.findViewById(R.id.rl_popupbox);
        rl_popupbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closePopupWindow(et_goods_store.getText().toString());
            }
        });

        //拦截点击事件，防止传到下一层rl_popupbox
        LinearLayout ll_popup_box=(LinearLayout)contentView.findViewById(R.id.ll_popup_box);
        ll_popup_box.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        ImageView iv_setnum_close=(ImageView)contentView.findViewById(R.id.iv_setnum_close);
        iv_setnum_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closePopupWindow(et_goods_store.getText().toString());
            }
        });

        //减
        LinearLayout ll_setnum_cut=(LinearLayout)contentView.findViewById(R.id.ll_setnum_cut);
        ll_setnum_cut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num = Integer.parseInt(et_goods_store.getText().toString());
                if(num>1){
                    num--;
                }
                et_goods_store.setText(String.valueOf(num));
            }
        });

        //加
        LinearLayout ll_setnum_add =(LinearLayout)contentView.findViewById(R.id.ll_setnum_add);
        ll_setnum_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num = Integer.parseInt(et_goods_store.getText().toString());
                if(num<goods.getGoodsStoreNum()){
                    num++;
                }
                et_goods_store.setText(String.valueOf(num));
            }
        });
    }

    private void closePopupWindow(String num){
        tv_goodsinfo_num.setText(num);
        mPopWindow.dismiss();
    }

    private void getComment(int goodsId){
        String url = "http://"+ Constant.host+":"+Constant.port+"/api/Comment/GetCommentByGoodsId/"+goodsId;
        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        gson = new Gson();
                        List<Comment> commentList=new ArrayList<Comment>();
                        commentList = gson.fromJson(result,new TypeToken<List<Comment>>(){}.getType());
                        if(commentList.size()>0) {
                            commentJson=result;
                            tv_goodsinfo_comment.setText(String.valueOf(commentList.size()));
                            ll_goodsinfo_comment=(LinearLayout)findViewById(R.id.ll_goodsinfo_comment);
                            ll_goodsinfo_comment.setOnClickListener(GoodsInfoActivity.this);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(GoodsInfoActivity.this, "网络请求失败",
                                Toast.LENGTH_LONG).show();
                    }
                }
        );
        request.setTag("getCommentList");
        MyApplication.getHttpQueue().add(request);
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束时队列里面注销
        MyApplication.getHttpQueue().cancelAll("getGoodsImgList");
        MyApplication.getHttpQueue().cancelAll("getCommentList");
    }
}
